
let courseId = ''
let videoId = ''

let track = null

let currentWord = ''

const getTrack = async () => {
  const res = await axios.get(`/ajax/player/transcript?courseId=${courseId}&videoId=${videoId}`)
  return res.data
}

  
if (document.querySelector('#courseplayer')) {
  
  utilVideoLoad().then(video => {

    const videoInfo = JSON.parse(video.dataset.conviva)
    
    videoId = videoInfo.VideoId
    courseId = videoInfo.CourseId
    
    console.log('Lynda Video Found!');
    console.log('Video URL: ' + videoInfo.Url)
  
    video.addEventListener('timeupdate', async e => {
      const word = await showText(e.target.currentTime*1000)

      word && chrome.runtime.sendMessage(word, () => {})
  
    })
  
    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
      const json = JSON.parse(request)
      if (json.data) {
        showTranslationResult(json.data)
      } else {
        console.log(`Error: ${json.message}`)
      }
      sendResponse(true)
    })

  })
  

}


async function utilVideoLoad () {
  let id = null
  return new Promise((resolve, reject) => {
    id = window.setInterval(() => {
      if (document.querySelector('.mejs-inner video')) {
        window.clearInterval(id)
        resolve(document.querySelector('.mejs-inner video'))
      }
    }, 300)
  })
}

async function showText (time) {
  if (!track) {
    const text = await getTrack()
    track = transformFormText(text) 
  }
  const text = track(time)
  return text
} 

function showTranslationResult(text) {
  let position = null
  const enDom = document.querySelector('.mejs-captions-position span')
  if (enDom) {
    const rect = enDom.getBoundingClientRect()
    position = {
      x: rect.x + rect.width / 2,
      y: rect.y + rect.height / 2 - 40
    }
  }
  let dom = document.querySelector('#lynda-translate-result')
  if (dom) {
    dom.innerHTML = text
  } else {
    dom = document.createElement('span')
    dom.id = 'lynda-translate-result'
    document.body.appendChild(dom)
  }
  dom.style.left = position.x + 'px'
  dom.style.top = position.y + 'px'
}



function transformFormText (text) {
  const reg = /(\d\d):.?(\d\d):.?(\d\d),.?(\d\d\d).?--.?>.?(\d\d):.?(\d\d):.?(\d\d),.?(\d\d\d)[\n\r]((.|\n|\r)+?)([\n\r]{2}|$)/


  const getInfoFormWrod = t => {
    const l = t.replace(reg, '$1~~$2~~$3~~$4~~$5~~$6~~$7~~$8~~$9').split('~~')
    return {
      start: +l[0] * 60 * 60 * 1000 + +l[1] * 60 * 1000 + +l[2] * 1000 + +l[3],
      end: +l[4] * 60 * 60 * 1000 + +l[5] * 60 * 1000 + +l[6] * 1000 + +l[7],
      word: l[8].replace(/[\n\r]/g, ' ').replace(/\s*$/, '')
    }
  }

  const combineWords = list => {
    let temp = null
    return list.reduce((all, cur, index, list) => {
      if (index !== list.length - 1 && !cur.word.match(/(\.|:|\?)$/)) {
        temp = temp ? { start: temp.start, end: cur.end, word: temp.word + ' ' + cur.word } : cur
        return all
      } else {
        all.push(temp ? { start: temp.start, end: cur.end, word: temp.word + ' ' + cur.word } : cur)
        temp = null
        return all
      }
    }, [])
  }

  const matches = text.match(/\d\d:.?\d\d:.?\d\d,.?\d\d\d.?--.?>.?\d\d:.?\d\d:.?\d\d,.?\d\d\d[\n\r](.|\n|\r)+?([\n\r]{2}|$)/g)

  const result = combineWords(matches.map(i => getInfoFormWrod(i)))

  console.log('English Subtitle Found.');
  

  return time => {
    const match = result.find(i => (i.start <= time && i.end > time))
    return match && match.word
  }
}